using BuildingBlocks.Application.Messaging;
using BuildingBlocks.Domain;
using Catalog.Api.Data;
using Catalog.Api.Features.CatalogItems.GetItems;
using Catalog.Api.Models;
using MongoDB.Driver;

namespace Catalog.Api.Features.CatalogItems.GetById;  
  
public sealed record GetCatalogItemByIdQuery(string Id) : IQuery<CatalogItemResponse>;  
  
internal sealed class GetCatalogItemByIdQueryHandler(CatalogDbContext context)  
    : IQueryHandler<GetCatalogItemByIdQuery, CatalogItemResponse>  
{  
    public async ValueTask<Result<CatalogItemResponse>> Handle(  
        GetCatalogItemByIdQuery request,  
        CancellationToken cancellationToken)  
    {  
        var filter = Builders<CatalogItem>.Filter.Eq(i => i.Id, request.Id);  
        var item = await context.CatalogItems.Find(filter).FirstOrDefaultAsync(cancellationToken);  
  
        if (item is null)  
        {  
            return Result.Failure<CatalogItemResponse>(CatalogItemErrors.NotFound(request.Id));  
        }  
  
        return Result.Success(Mapper.ToResponse(item));  
    }  
}
